package com.yinhai.message.core.bpo;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.yinhai.core.common.api.config.impl.SysConfig;
import com.yinhai.core.common.api.util.ValidateUtil;
import com.yinhai.core.service.ta3.domain.service.TaBaseService;
import com.yinhai.message.api.bean.TMAppMessage;
import com.yinhai.message.api.bean.TMMessage;
import com.yinhai.message.api.bean.TMUser;
import com.yinhai.message.api.bean.TMWeChat;
import com.yinhai.message.api.util.MessageType;
import com.yinhai.message.api.vo.TMMessageVo;
import com.yinhai.message.core.dao.IAppMessageDao;
import com.yinhai.message.core.dao.IMessageDao;
import com.yinhai.message.core.dao.IMessageDetailDao;
import com.yinhai.message.core.dao.IMessageFileDao;
import com.yinhai.message.core.po.AppMessagePo;
import com.yinhai.message.core.po.MessageDetailPo;
import com.yinhai.message.core.po.MessageFilePo;
import com.yinhai.message.core.po.MessagePo;
import com.yinhai.message.core.po.id.MessageDetailId;
import com.yinhai.message.core.util.IMessageConstant;
import com.yinhai.message.manage.msgmg.vo.MessageDetailVo;
import com.yinhai.message.manage.wxregister.bpo.IWxConfigBpo;


public class MessageBpoImpl extends TaBaseService implements IMessageBpo {

    @Resource(name = "messageDao")
    private IMessageDao messageDao;

    @Resource(name = "messageDetailDao")
    private IMessageDetailDao messageDetailDao;

    @Resource(name = "messageFileDao")
    private IMessageFileDao messageFileDao;
    
    @Resource(name = "wxConfigBpo")
    private IWxConfigBpo wxConfigBpo;
    
    @Resource(name = "appMessageDao")
    private IAppMessageDao appMessageDao;
    
    @Override
    public List<MessageDetailVo> queryMessageDetailsByMsgId(String messageId) {
        Map<String,String> param = new HashMap<>();
        param.put("messageId", messageId);
        StringBuffer hql = new StringBuffer();
        hql.append("select new com.yinhai.message.manage.msgmg.vo.MessageDetailVo(")
                .append("mdp.id.mgid,")
                .append("mdp.id.userid,")
                .append("mdp.id.systemid,")
                .append("mdp.id.sendertype,")
                .append("mdp.senddate,")
                .append("mdp.errorinfo,")
                .append("mdp.state,")
                .append("mdp.read,")
                .append("mdp.showtype,")
                .append("u.name,")
                .append("map.systemname")
                .append(") from MessageDetailPo mdp ,")
                .append(SysConfig.getSysConfig("com.yinhai.modules.org.ta3.domain.po.impl.UserPo", "com.yinhai.modules.org.ta3.domain.po.impl.UserPo"))
                .append("  u, MessageAppManagePo map")
                .append(" where 1=1 and u.userid = mdp.id.userid and mdp.id.systemid = map.systemid").append(" and mdp.id.mgid  =:messageId");
        return messageDao.queryMessageDetailsByMsgId(hql.toString(), param);
    }

    @Override
    public void addMessage(TMMessageVo amqVo) throws Exception {
        MessagePo po = new MessagePo();
        TMMessage message = amqVo.getMessage();
        TMUser suser = amqVo.getUser();
        po.setMsgid(message.getMgid());
        po.setTitle(message.getTitle());
        po.setMsgcontent(message.getContent().getBytes("UTF-8"));
        po.setMsgdate(message.getCreateDate());
        po.setSenduserid(suser.getUserId());
        po.setSendsystemid(suser.getAppId());
        po.setSelfType(message.getSelfType());
        po.setOtherData1(message.getOtherData1());
        po.setOtherData2(message.getOtherData2());
        po.setOtherData3(message.getOtherData3());
        messageDao.save(po);
    }

    @Override
    public void addMessage(MessagePo po) {
        messageDao.save(po);
    }

    @Override
    public void addMessageState(MessageDetailPo po) {
        messageDetailDao.save(po);
    }

    @Override
    public void modifyMessageSate(MessageDetailPo po) {
        po.setSenddate(getSysTimestamp());
        messageDetailDao.update(po);
    }
    
    @Override
	public void modifyMessageSateBatch(List<MessageDetailPo> poList) {
    	messageDetailDao.updateBatch(poList);
	}

	@Override
	public List<MessageFilePo> queryMessageFileByMsgid(String msgid) {
		return messageFileDao.queryByMsgid(msgid);
	}
	
   
	/**
	 * 持久化消息主体 和 明细
	 * @param vo
	 * @return
	 * @throws Exception
	 */
	@Override
	public String saveMessage(TMMessageVo vo) throws Exception{
		 //步骤2.存储消息主数据
        MessagePo po = new MessagePo();
        TMMessage message = vo.getMessage();
        message.setCreateDate(new Date(getSysTimestamp().getTime()));
        TMUser senduer = vo.getUser();
        po.setMsgid(message.getMgid());
        po.setTitle(message.getTitle());
        po.setMsgcontent(message.getContent().getBytes("UTF-8"));
        po.setMsgdate(message.getCreateDate());//
        po.setSenduserid(senduer.getUserId());
        po.setSendsystemid(senduer.getAppId());
        po.setSname(senduer.getName());
        po.setSelfType(message.getSelfType());
        po.setOtherData1(message.getOtherData1());
        po.setOtherData2(message.getOtherData2());
        po.setOtherData3(message.getOtherData3());
        messageDao.save(po);
        //步骤3.存储明细数据
        String mgid = message.getMgid();
        List<String> messageTypes = message.getMessageTypes();
        List<MessageDetailPo> detailPoList = new ArrayList<>();
        for (String msgType:messageTypes) {
        	if(msgType.equals(MessageType.WECHAT)){
        		TMWeChat wx = vo.getWechat(); 
        		if(ValidateUtil.isEmpty(wx)){
        			wx = wxConfigBpo.getDefaultWx();
        			vo.setWechat(wx);
        		}
				if (message.isToAlluser()) {
					MessageDetailPo detailPo = new MessageDetailPo();
					MessageDetailId detailId = new MessageDetailId();
					detailId.setMgid(mgid);
					detailPo.setState(IMessageConstant.MSG_STATE_SEND_NOW);
					detailId.setSendertype(msgType);
					detailId.setUserid(IMessageConstant.WX);
					detailId.setSystemid(IMessageConstant.WX);
					detailPo.setId(detailId);
					detailPo.setAppid(wx.getAppid());
					detailPo.setSenddate(getSysTimestamp());
					detailPoList.add(detailPo);
				} else {
					for (TMUser user : vo.getUserlist()) {
						MessageDetailPo detailPo = new MessageDetailPo();
						MessageDetailId detailId = new MessageDetailId();
						detailId.setMgid(mgid);
						detailPo.setState(IMessageConstant.MSG_STATE_SEND_NOW);
						detailId.setSendertype(msgType);
						detailId.setUserid(user.getUserId());
						detailId.setSystemid(user.getAppId());
						detailPo.setId(detailId);
						detailPo.setAppid(wx.getAppid());
						detailPo.setSenddate(getSysTimestamp());
						detailPoList.add(detailPo);
					}
				}
        	}else{
        		for (TMUser user : vo.getUserlist()) {
        			MessageDetailPo detailPo = new MessageDetailPo();
                	MessageDetailId detailId = new MessageDetailId();
                	detailId.setMgid(mgid);
                	detailPo.setState(IMessageConstant.MSG_STATE_SEND_NOW);
                	detailId.setSendertype(msgType);
            		detailId.setUserid(user.getUserId());
                	detailId.setSystemid(user.getAppId());
                	detailPo.setId(detailId);
					detailPo.setSenddate(getSysTimestamp());
					detailPoList.add(detailPo);
            	}
        	}
        }
        messageDetailDao.batchSave(detailPoList);
        return mgid;
	}

	@Override
	public void batchSaveFile(List<MessageFilePo> filePoList) {
		messageFileDao.bathchSave(filePoList);
	}

	@Override
	public List<TMMessageVo> queryErrorMessageDetails() {
		return messageDetailDao.queryErrorMessageDetails();
	}

	@Override
	public void modifyErrorMessageDetail(List<MessageDetailPo> poList) {
		messageDetailDao.updateBatchByReSend(poList);
	}

	/**
	 * app
	 */
	@Override
	public void addAppMessage(TMAppMessage appMessage,String aac001s) {
		String aac[] = aac001s.split(",");
		for(String aac001:aac){
			AppMessagePo po = new AppMessagePo();
			po.setAac001(aac001);
			po.setMgcontent(appMessage.getContent());
			po.setTitle(appMessage.getTitle());
			po.setSelfType(appMessage.getSelfType());
			po.setMgdate(getSysDate());
			appMessageDao.saveApp(po);
		}
	}

}
